package com.jeff.android.lab.jframework.app;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import androidx.annotation.RequiresPermission;

import java.util.LinkedList;
import java.util.List;

/**
 * @author: duff
 * @date: 2019/1/14
 * @since: 1.0.0
 */
public class NetworkChangeReceiver extends BroadcastReceiver {
    ConnectivityManager mConnectivityManager;
    List<NetworkChangeListener> mListeners = new LinkedList<>();

    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ("android.net.conn.CONNECTIVITY_CHANGE".equals(action)) {
            if (isNetWorkAvailable(context)) {
                notifyConnected();
            } else {
                notifyDisconnected();
            }
        }
    }

    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    private boolean isNetWorkAvailable(Context context) {
        if (mConnectivityManager == null) {
            mConnectivityManager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        }
        if (mConnectivityManager != null) {
            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
        return false;
    }

    private void notifyConnected() {
        for (NetworkChangeListener l : mListeners)
            l.onConnect();
    }

    private void notifyDisconnected() {
        for (NetworkChangeListener l : mListeners)
            l.onDisconnect();
    }

    public void addListener(NetworkChangeListener l) {
        if (l != null && !mListeners.contains(l))
            mListeners.add(l);
    }

    public void removeListener(NetworkChangeListener l) {
        if (l != null && mListeners.contains(l))
            mListeners.remove(l);
    }

}
